package org.michael.u.brg.by.spring.aop.abcthreads;

import java.util.concurrent.ExecutorService;

/**
 * Spawns the B runner, watches the execution time, shuts down the thread pool if overlimit.
 */
public class RunnerA extends Thread {
	
	private ExecutorService exec;
	private Long id;
	
	private long delay; 
	
	private long startupMillis;
	
	private long maxMillisToRun;
	
	private RunnerB b;
	
	public void init() {
	}

	@Override
	public void run() {
		final long now = System.currentTimeMillis();
		System.out.printf("%nA#%d: started at %,d", id, now - startupMillis);
		if( (now - startupMillis) < maxMillisToRun) { // still have time?
			try { Thread.sleep(delay); } catch(InterruptedException x) {x.printStackTrace();}
			Thread bt = new Thread(b, "B-" + b.getId() + "/" + id);
			exec.execute(bt);
		}
		else { // over time limit, shut down the thread pool
			System.out.printf("%n----Done!");
			exec.shutdown();
		}
		System.out.printf("%nA#%d: ended at %,d", id, System.currentTimeMillis() - startupMillis);
	}

	public RunnerB getB() {
		return b;
	}
	
	public void setB(RunnerB value) {
		this.b = value;
	}
	
	public void setIdGetter(IdProvider id) {
		this.id = id.getNext();
		setName("A#" + id);
	}
	
	public void setExec(ExecutorService svc) {
		this.exec = svc;
	}
	
	public Long getRunnerId() {
		return id;
	}
	
	public void setDelay(Long delay) {
		this.delay = delay;
	}
	public void setStartupMillis(long startupMillis) {
		this.startupMillis = startupMillis;
	}
	public void setMaxMillisToRun(long maxMillisToRun) {
		this.maxMillisToRun = maxMillisToRun;
	}
	
	
}
